package com.shut.vehicle.dao.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 卢斌
 */
@MappedJdbcTypes({JdbcType.TINYINT, JdbcType.INTEGER, JdbcType.BIGINT})
@MappedTypes({Boolean.class})
public class BooleanHandler implements TypeHandler<Boolean> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        if (aBoolean == null) {
            preparedStatement.setObject(i, null);
        } else {
            if (aBoolean) {
                preparedStatement.setInt(i, 1);
            } else {
                preparedStatement.setInt(i, 0);
            }
        }
    }

    @Override
    public Boolean getResult(ResultSet resultSet, String s) throws SQLException {
        Integer result = resultSet.getObject(s, Integer.class);
        if (result == null) {
            return null;
        }
        return result > 0;
    }

    @Override
    public Boolean getResult(ResultSet resultSet, int i) throws SQLException {
        Integer result = resultSet.getObject(i, Integer.class);
        if (result == null) {
            return null;
        }
        return result > 0;
    }

    @Override
    public Boolean getResult(CallableStatement callableStatement, int i) throws SQLException {
        Integer result = callableStatement.getObject(i, Integer.class);
        if (result == null) {
            return null;
        }
        return result > 0;
    }
}
